﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace DataAccess
{
    public class DBDAO
    {
        public void BackupDB(string strFilePath)
        {
            // 可以成功备份数据库，但未备份日志，无法正常导入。
            SqlConnection con = null;
            try
            {
                con = DataAccess.ConnectionManager.getInstance().getConnection();
                string strSql = @"BACKUP DATABASE DB_RMS TO Disk='" + strFilePath + "';";
                Console.WriteLine(strSql);
                SqlCommand cmd = new SqlCommand(strSql, con);
                cmd.ExecuteNonQuery();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw new Exception("连接数据库失败！备份数据库操作不成功！");
            }
            finally
            {
                if (con != null) { con.Close(); con.Dispose(); con = null; }
            }
        }
        public void RecoveryDB(string strFilePath)
        {
            // 不成功，无法正常执行：数据库存在其它连接，无法解决这个问题
            SqlConnection con = null;
            try
            {
                con = ConnectionManager.getInstance().getConnection();
                string strSql = "RESTORE DATABASE DB_RMS FROM DISK='" + strFilePath + "';";
                Console.WriteLine(strSql);
                SqlCommand cmd = new SqlCommand(strSql, con);
                cmd.ExecuteNonQuery();
            }
            catch (System.IO.FileNotFoundException exc1)
            {
                throw new Exception("备份文件不存在！");
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw new Exception("连接数据库失败！恢复数据库操作不成功！");
            }
            finally
            {
                if (con != null) { con.Close(); con.Dispose(); con = null; }
            }
        } // end of function
    }
}
